//app.js
App({
  //传递参数
  transferParameter: {},
  tips: {
    noPageData: "没有更多数据了",
    error: "服务器异常,请稍后再试"
  },
  //接口地址定议
  url: {
    //baseUrl: "http://192.168.1.103/wechat",
    baseUrl: "http://localhost/wechat",
    uploadUrl: "http://localhost",
    downLoadUrl: "http://localhost",
  },
  //常量值
  keys: {
    USER_INFO: "USER_INFO", //用户信息
    INTERFACE_TOKEN: "INTERFACE_TOKEN",//接口返回的token
    IS_LOGIN_IN: false,
    AUTH_INFO: "authInfo",
    SCORE_LI: "scoreLi",
    BANNER: "banner",
  },
  onLaunch: function () {
    // this.checkUserIsLogin()
  },
  //检测用户是否登陆
  // checkUserIsLogin: function () {
  //   if (this.keys.IS_LOGIN_IN)
  //     return
  //   var that = this
  //   wx.login({
  //     success: function (res) {
  //       that.keys.IS_RELOGIN = false
  //       console.log("获取用户登陆code")
  //       if (res.code) {
  //         var data = { code: res.code };
  //         that.getAuthorization(data)
  //       } else {
  //         console.log('获取用户登录态失败！' + res.errMsg)
  //       }
  //     }, fail: function (res) {
  //       console.log("获取用户code失败")
  //       console.log(res)
  //     }
  //   })
  // },
  //获取用户authorization并更新用户
  getAuthorization: function (data) {
    var that = this
    wx.request({
      url: that.url.baseUrl + "/login",
      method: 'POST',
      data: data,
      header: { "Content-Type": "application/x-www-form-urlencoded" },
      success: function (res) {
        console.log("code发送调用成功");
        that.setStorage(that.keys.INTERFACE_TOKEN, res.data.token);
        that.keys.IS_LOGIN_IN = false //登陆完成
        //获取用户信息
        wx.getUserInfo({
          success: function (res) {
            console.log("调用用户信息成功");
            var userInfo = res.userInfo
            var nickName = userInfo.nickName
            var avatarUrl = userInfo.avatarUrl
            var gender = userInfo.gender //性别 0：未知、1：男、2：女
            userInfo = { sex: gender, headIcon: avatarUrl, nickName: nickName };
            //console.log(res);
            //更新用户 
            that.ajax(that.url.baseUrl + "/authUpUser", userInfo, function (res) {
              that.setStorage(that.keys.USER_INFO, res.data.data);
            });
          }, fail: function (res) {
            console.log("调用用户信息失败")
          }
        });
      }, fail: function (res) {
        console.log("网络异常,请稍候再试")
      }
    })
  },
  /**
 * ajax请求
 * url:请求地址
 * data:json数据
 * s:成功回调如无需要可填null
 * f:失败回调,如无需要可填null
 * h:头部信息,如果无特殊要求可填null
 */
  ajax: function (url, data, s, f, h) {
    console.log(url)
    var that = this
    var data = data == null ? {} : data
    var h = h == null ? {} : h
    if (h["Content-Type"] == null) {
      h["Content-Type"] = "application/json"
    }
    var authorization = this.getStorage(this.keys.INTERFACE_TOKEN)

    //如果用户清除了缓存
    if (authorization == null || authorization == '') {
      that.checkUserIsLogin()
      setTimeout(function () {
        that.ajax(url, data, s, f, h)
      }, 3000)
      that.keys.IS_LOGIN_IN = true
      return
    }
    authorization = this.getStorage(this.keys.INTERFACE_TOKEN)
    h["authorization"] = authorization
    wx.request({
      url: url,
      data: data,
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: h, // 设置请求的 header
      success: function (res) {
        var statusCode = res.statusCode
        if (statusCode == 401) {
          that.checkUserIsLogin()
          setTimeout(function () {
            that.ajax(url, data, s, f, h)
          }, 3000)
          that.keys.IS_LOGIN_IN = true
          return
        }
        if (s != null)
          s(res);
      },
      fail: function (res) {
        if (f != null)
          f(res);
      },
      complete: function (res) {

      }
    })
  },
  //正则表达式
  regs: {
    number: /^[0-9]*$/,//数字
    phone: /^1\d{10}$/,//手机
  },
  //提交验证
  valids: function (value, validType) {
    if (validType == "notEmpty") {
      if (value.replace(/(^s*)|(s*$)/g, "").length == 0)
        return false
      return true
    }
    var reg = this.regs[validType]
    if (reg.test(value))
      return true
    return false
  },
  /**
  * 设置key
  */
  setStorage: function (k, v) {
    wx.setStorageSync(k, v);
  },
  /**
   * 移除key
   */
  removeStorage: function (k) {
    wx.removeStorage({ key: k });
  },
  /**
   * 读取key
   */
  getStorage: function (k) {
    return wx.getStorageSync(k);
  },
})